package com.ddstation.app.waste_delivery.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import com.ddstation.common.service.InvsItemInstitutionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.common.entity.DdPictureEntity;
import com.ddstation.common.mapper.DdPictureMapper;
import com.ddstation.common.util.AliCloudOssUtil;
import com.ddstation.common.util.CheckUtil;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionEntity;
import com.ddstation.crm.institution.service.InstitutionService;
import com.ddstation.crud.entity.DtInvsWasteDeliveryDetailEntity;
import com.ddstation.crud.entity.DtInvsWasteDeliveryEntity;
import com.ddstation.waste_delivery.service.WasteDeliveryService;

import net.sf.json.JSONArray;

@Controller
public class AppWasteDeliveryController {

	@Inject private InvsItemInstitutionService invsItemInstitutionService;
	@Inject private WasteDeliveryService wasteDeliveryService;
	@Inject private DdPictureMapper ddPictureMapper;
	@Inject private InstitutionService institutionService;

	/**
	 * (医疗废弃物登记)获取历史记录
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/history", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsWasteDeliveryHistoryEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
//		String institutionId = "00000012";
		String pageSize = params.get("pageSize").toString();
		String pageNo = params.get("pageNo").toString();
		DtHealthManageInstitutionEntity institutionEntity = institutionService.get(institutionId);
		retMap.put("unit",institutionEntity.getInvsUnit());
		retMap.put("itemList",wasteDeliveryService.selectByHistory(institutionId,Integer.parseInt(pageNo),Integer.parseInt(pageSize)));
		retMap.put("errCode", 0);
		retMap.put("errorMsg", "");
		return retMap;

	}

	/**
	 * (医疗废弃物处理登记)上传记录
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/save", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsWushuiCheckSaveEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
				|| CheckUtil.isEmpty(params.get("currentTime"))
				|| CheckUtil.isEmpty(params.get("sourceCode"))
				|| CheckUtil.isEmpty(params.get("deliveryType"))
				|| CheckUtil.isEmpty(params.get("wasteType"))
				|| CheckUtil.isEmpty(params.get("unit"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
		Integer doctorId = Integer.parseInt(params.get("doctorId").toString());
		String currentTimeStr = params.get("currentTime").toString();
		String sourceCode = params.get("sourceCode").toString();
		String deliveryType = params.get("deliveryType").toString();
		String wasteType = params.get("wasteType").toString();
		String attachmentId = CheckUtil.isEmpty(params.get("attachmentId"))? null : params.get("attachmentId").toString();
		Integer unit = Integer.parseInt(params.get("unit").toString());
		//Integer unit = 1;
		DtInvsWasteDeliveryEntity entity = new DtInvsWasteDeliveryEntity();
		entity.setCreateTm(new Date());
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat f2 = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
		Calendar cal = Calendar.getInstance();
		Date currentDate = null;
		Date currentTime = null;
		try {
			currentDate = f.parse(currentTimeStr + ":00");
			cal.setTime(currentDate);
			entity.setDeliveryDt(cal.getTime());
			currentTime = f2.parse(currentTimeStr + ":00");
			cal.setTime(currentTime);
			entity.setDeliveryTm(cal.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		entity.setDeliveryType(Integer.parseInt(deliveryType));
		entity.setDoctorId(doctorId);
		entity.setInstitutionId(institutionId);
		entity.setReceiptImgId(attachmentId);
		entity.setSource(Integer.parseInt(sourceCode));

		List<DtInvsWasteDeliveryDetailEntity> detailEntityList = new ArrayList<DtInvsWasteDeliveryDetailEntity>();
		try {
			JSONArray jsonBean = JSONArray.fromObject(wasteType);
			for(int i=0; i<jsonBean.size(); i++) {
				DtInvsWasteDeliveryDetailEntity detailEntity = new DtInvsWasteDeliveryDetailEntity();
				detailEntity.setWasteType(i+1);
				detailEntity.setQuantity(Float.valueOf(jsonBean.getString(i)));
				detailEntity.setUnit(unit);
				detailEntityList.add(detailEntity);
			}
		} catch (Exception e) {
			retMap.put("errCode", -1);
			retMap.put("errormsg", "请填写数量（数值类型）");
			return retMap;
		}
		wasteDeliveryService.addWasteDelivery(institutionId,doctorId,entity,detailEntityList);
		retMap.put("errCode", 0);
		retMap.put("errormsg", "");
		return retMap;
	}

	/**
	 * (医疗废弃物处理登记)详细
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/detail", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsWushuiCheckDetailEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
				|| CheckUtil.isEmpty(params.get("id"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
		Integer id = Integer.parseInt(params.get("id").toString());
		DtInvsWasteDeliveryEntity infoEntity = wasteDeliveryService.wasteDeliveryDetail(institutionId,id);
		retMap.put("info", infoEntity);

		List<String> thumbImgList = new ArrayList<String>();
		List<String> originImgList = new ArrayList<String>();
		if (infoEntity.getReceiptImgId()!=null) {
			for (String m_id:infoEntity.getReceiptImgId().split(",")) {
				if (!CheckUtil.isEmpty(m_id)) {
					DdPictureEntity picture = ddPictureMapper.selectOne(m_id);
					if (picture.getPath().endsWith("pdf") || picture.getPath().endsWith("PDF")
							|| picture.getPath().endsWith("xls") || picture.getPath().endsWith("xlsx")
							|| picture.getPath().endsWith("XLS") || picture.getPath().endsWith("XLSX")
							|| picture.getPath().endsWith("doc") || picture.getPath().endsWith("docx")
							|| picture.getPath().endsWith("DOC") || picture.getPath().endsWith("DOCX")) {
						continue;
					}
					thumbImgList.add(AliCloudOssUtil.getThumbImgUrl(null, picture.getPath(), "@100h"));
					originImgList.add(AliCloudOssUtil.getThumbImgUrl(null, picture.getPath(), "@800h"));
				}
			}
		}
		retMap.put("originImgList",originImgList);
		retMap.put("thumbImgList",thumbImgList);
		retMap.put("errCode", 0);
		retMap.put("errorMsg", "");
		return retMap;
	}

	/**
	 * (医疗废弃物处理登记)获取来源、处置方式
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/getInvsItem", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsItemXdjEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
		//retMap.put("list",invsItemService.getInvsItemList(5));
		//判断是否第一次
		if (!(invsItemInstitutionService.selectInvsItemAllCnt(15,institutionId) > 0)) {
			// 初始化数据
			invsItemInstitutionService.init(15,institutionId);
		}
		retMap.put("sourceList",invsItemInstitutionService.selectShowInvsItem(15,institutionId));
		//判断是否第一次
		if (!(invsItemInstitutionService.selectInvsItemAllCnt(16,institutionId) > 0)) {
			// 初始化数据
			invsItemInstitutionService.init(16,institutionId);
		}
		retMap.put("deliveryList",invsItemInstitutionService.selectShowInvsItem(16,institutionId));
		retMap.put("errCode", 0);
		retMap.put("errorMsg", "");
		return retMap;

	}

	/**
	 * (医疗废弃物处理登记)获取所有来源、处置方式
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/pageLoad", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsWasteDeliveryPageLoadEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
		retMap.put("sourceList",invsItemInstitutionService.getInvsItemInstitutionList(15,institutionId));
		retMap.put("deliveryList",invsItemInstitutionService.getInvsItemInstitutionList(16,institutionId));
		retMap.put("errCode", 0);
		retMap.put("errorMsg", "");
		return retMap;

	}


	/**
	 * (医疗废弃物处理登记)保存显示的来源、处置方式
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/saveShowItem", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsWasteDeliverySaveShowItemEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
				|| CheckUtil.isEmpty(params.get("ids1"))
				|| CheckUtil.isEmpty(params.get("ids2"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
		String ids1 = params.get("ids1").toString();
		String ids2 = params.get("ids2").toString();
		invsItemInstitutionService.saveInvsItem(15,institutionId,ids1);
		invsItemInstitutionService.saveInvsItem(16,institutionId,ids2);
		retMap.put("errCode", 0);
		retMap.put("errorMsg", "");
		return retMap;
	}

	/**
	 * (器械/场所消毒登记)新增器械/场所
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/addItem", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsWasteDeliveryAddItemEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
				|| CheckUtil.isEmpty(params.get("instrumentType"))
				|| CheckUtil.isEmpty(params.get("name"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
		Integer instrumentType = Integer.parseInt(params.get("instrumentType").toString());
		Integer catalogId = 0;
		if (instrumentType == 1) {
			catalogId = 15;
		} else {
			catalogId = 16;
		}
		String name = params.get("name").toString();
		List<String> list = invsItemInstitutionService.checkByInvsItemName(catalogId,institutionId,name);
		if (list != null && list.size()>0) {
			retMap.put("errCode", -2);
			return retMap;
		}
		int cnt = invsItemInstitutionService.addInvsItem(catalogId,institutionId,name,null);
		if (cnt == 1)
			retMap.put("errCode", 0);
		retMap.put("errorMsg", "");
		return retMap;
	}

	/**
	 * (器械/场所消毒登记)删除器械/场所
	 * @param params
	 * @return
	 */
	@RequestMapping(value="appinvs_waste_delivery.do/delItem", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> invsWasteDeliveryDelItemEvent(
			@RequestBody Map<String, Object> params) {

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errCode", -1);
		if (params.isEmpty() || CheckUtil.isEmpty(params.get("institutionId"))
				|| CheckUtil.isEmpty(params.get("instrumentType"))
				|| CheckUtil.isEmpty(params.get("id"))) {
			return retMap;
		}
		String institutionId = params.get("institutionId").toString();
		Integer instrumentType = Integer.parseInt(params.get("instrumentType").toString());
		Integer id = Integer.parseInt(params.get("id").toString());
		Integer catalogId = 0;
		if (instrumentType == 1) {
			catalogId = 15;
		} else {
			catalogId = 16;
		}
		int cnt = invsItemInstitutionService.delInvsItem(catalogId,institutionId,id);
		if (cnt == 1)
			retMap.put("errCode", 0);
		retMap.put("errorMsg", "");
		return retMap;
	}
}
